﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.InteropServices.ComTypes;
using System.Xml.Linq;
using UnityEngine;

public class MsgPanelData
{
    public List<Apply> applications;
    public List<Chat> chats;
}

public partial class MsgPanel : MonoBehaviour
{
    List<ApplicationItem> m_ApplicationItems = new List<ApplicationItem>();
    public Transform applicationItemsParent;
    public ApplicationItem applicationItemPref;

    public Transform applicationsPanelBtn;

    List<ChatCandidateItem> m_ChatCandidateItems = new List<ChatCandidateItem>();
    public Transform chatCandidateItemsParent;
    public ChatCandidateItem chatCandidateItemPref;

    MsgPanelData m_Data;
    public void Init(MsgPanelData data)
    {
        m_Data = data;

        InitApplications(data);
        InitChats(data);
    }

    void InitApplications(MsgPanelData data)
    {
        UnityFunctions.ClearList(m_ApplicationItems);
        UnityFunctions.ClearList(m_ChatCandidateItems);

        for (int i = 0; i < data.applications.Count; i++)
        {
            if (data.applications[i].targetUserId != MGame.instance.MUser.id
                || data.applications[i].result != Apply.Applying)
                continue;

            var newItem = Instantiate(applicationItemPref, applicationItemsParent);
            newItem.gameObject.SetActive(true);
            newItem.Init(data.applications[i], OnSelectApplicationItem);

            m_ApplicationItems.Add(newItem);
        }
        applicationsPanelBtn.SetAsLastSibling();

    }

    void InitChats(MsgPanelData data)
    {
        UnityFunctions.ClearList(m_ChatCandidateItems);

        List<ChatData> uniChats = new List<ChatData>();

        foreach(var chat in data.chats)
        {
            if(chat.userId1 == MGame.instance.MUser.id)
            {
                //发的消息
                uniChats.Add(new ChatData(chat.userId1,chat.userId2, chat,null));
            }
            else
            {
                //收的消息
                ChatData exist = uniChats.Find(e => e.opponentUserId == chat.userId1);
                if (exist == null)
                {
                    uniChats.Add(new ChatData(chat.userId2, chat.userId1, null, chat));
                }
                else
                {
                    exist.opponentChat = chat;
                }
            }
        }

        var oppoIds = uniChats.Map(e => e.opponentUserId).AsArray();
        
        MGame.instance.localDataController.GetMiniUserInfo(
       // RequestServerController.instance.RequestMiniUserInfo(
            oppoIds, (uis) =>
        {
            if (uis.Length != oppoIds.Length)
            {
                GameDebug.LogError($"uis.Length:{uis.Length}  !=  oppoIds.Length:{oppoIds.Length}");
                return;
            }

            for (int i = 0; i < uniChats.Count; i++)
            {
                var newItem = Instantiate(chatCandidateItemPref, chatCandidateItemsParent);
                newItem.gameObject.SetActive(true);

                Chat chat = null;
                ChatData chatData = uniChats[i];

                if (chatData.myChat != null && chatData.opponentChat != null)
                {
                    var myDialogues = chatData.myChat.dialogues;
                    var oppoDialogues = chatData.opponentChat.dialogues;
                    if (myDialogues[myDialogues.Length - 1].time > oppoDialogues[oppoDialogues.Length - 1].time)
                        chat = chatData.myChat;
                    else
                        chat = chatData.opponentChat;
                }
                else if (chatData.myChat != null && chatData.opponentChat == null)
                {
                    chat = chatData.myChat;
                }
                else if (chatData.myChat == null && chatData.opponentChat != null)
                {
                    chat = chatData.opponentChat;
                }
                else
                {
                    continue;
                }

                newItem.Init(uis[i], chat, OnSelectChatCandidateItem);

                m_ChatCandidateItems.Add(newItem);
                newItem.transform.SetAsFirstSibling();
            }
        });
           
    }

    void Start()
    {
        applicationItemPref.gameObject.SetActive(false);
        chatCandidateItemPref.gameObject.SetActive(false);
    }


    public void OnSelectApplicationItem(ApplicationItem item)
    {
        ApplyUserPanel view = this.GetComponentInParent<UIController>().ShowUI<ApplyUserPanel>();
        view.Init(this.m_Data.applications.Find(e => e.targetUserId == item.data.targetUserId));
    }

    public void OnClickShowApplyPanel()
    {
        var appPanel = this.GetComponentInParent<UIController>().ShowUI<ApplyPanel>();
        appPanel.Init(new ApplyPanelData() {applies = m_Data.applications});
    }

    public void OnSelectChatCandidateItem(ChatCandidateItem item)
    {
        long mUser = MGame.instance.MUser.id;
        long targetUserId = item.chatData.userId2 != MGame.instance.MUser.id ? item.chatData.userId2 : item.chatData.userId1; ;
        RequestServerController.instance.RequestUserInfo(targetUserId, (targetuserInfo) =>
        {
            var user1Chat = MGame.instance.MUser.chats.Find(e => e.userId1 == mUser && e.userId2 == targetUserId);
            var user2Chat = MGame.instance.MUser.chats.Find(e => e.userId1 == targetUserId && e.userId2 == mUser);
            ChatData chatData = new ChatData()
            {
                myUserId = mUser,
                opponentUserId = targetUserId,
                myChat = user1Chat,
                opponentChat = user2Chat,
            };
            ChatPanel view = this.GetComponentInParent<UIController>().ShowUI<ChatPanel>();
            view.Init(targetuserInfo, chatData);
        });
       
        if (item.chatData != null)
        {
            item.chatData.newMsgCount = 0;
            MGame.instance.MUser.UpdateChat(item.chatData);
        }
        InitChats(this.m_Data);
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
